package com.xyy.saas.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xyy.saas.payment.constants.Constants;
import com.xyy.saas.payment.dao.model.PayFinanceRefundPlan;
import com.xyy.saas.payment.exception.PaymentException;
import com.xyy.saas.payment.manage.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.manage.cores.vo.ResultPageVo;
import com.xyy.saas.payment.manage.cores.vo.ResultVO;
import com.xyy.saas.payment.pojo.dto.ProfitSharingSettleDTO;
import com.xyy.saas.payment.pojo.vo.PayFinanceRefundPlanVo;
import com.xyy.saas.payment.pojo.vo.PinganRepaymentPlanParamVO;
import com.xyy.saas.payment.pojo.vo.ProfitSharingVO;
import com.xyy.saas.payment.pojo.vo.UserAccountWithdrawalDTO;
import com.xyy.saas.payment.service.PinganLoanService;
import com.xyy.saas.payment.util.ExportExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = {"/pinganLoan"})
public class PinganLoanController {
    @Resource
    private PinganLoanService paymentLoanService;

    /**
     * 查询平安可提现金额
     */
    @GetMapping("/withdrawableBalance")
    public ResultVO<String> withdrawableBalance(@RequestParam(name = "userId") String userId) {
        try {
            return ResultVO.createSuccess(paymentLoanService.queryPinganWithdrawableBalance(userId));
        } catch (PaymentException pe) {
            return ResultVO.createError(pe.getErrCode(), pe.getMessage());
        } catch (Exception e) {
            return ResultVO.createError(e.getMessage());
        }
    }

    /**
     * 查询平安冻结金额
     */
    @GetMapping("/frozenAmount")
    public ResultVO<String> frozenAmount(@RequestParam(name = "userId") String userId) {
        try {
            return ResultVO.createSuccess(paymentLoanService.queryPinganFrozenAmount(userId));
        } catch (PaymentException pe) {
            return ResultVO.createError(pe.getErrCode(), pe.getMessage());
        } catch (Exception e) {
            return ResultVO.createError(e.getMessage());
        }
    }

    /**
     * 查询未分账订单
     */
    @GetMapping("/queryUnsettle")
    public ResultVO<List<ProfitSharingVO>> queryUnsettle(@RequestParam(name = "userId") String userId) {
        if (StringUtils.isBlank(userId)) {
            return ResultVO.createError(ResultCodeEnum.PARAM_ERROR);
        }

        // mock
        ProfitSharingVO profitSharingVO = new ProfitSharingVO();
        profitSharingVO.setBusinessOrderNo("YBM20241003124335132511");
        profitSharingVO.setPayNo("1841700613029642322");
        profitSharingVO.setShareState(8);
        profitSharingVO.setFinishSettleAmount("495.09");
        profitSharingVO.setUnFinishSettleAmount("0");
        profitSharingVO.setSurplusSettleAmount("0");

        List<ProfitSharingVO> voList = new ArrayList<>();
        voList.add(profitSharingVO);

        return ResultVO.createSuccess(voList);
    }

    /**
     * 分账
     */
    @PostMapping("/settle")
    public ResultVO<?> settle(@RequestBody ProfitSharingSettleDTO settleDTO) {
        try {
            paymentLoanService.settle(settleDTO);
            return ResultVO.createSuccess();
        } catch (PaymentException pe) {
            return ResultVO.createError(pe.getErrCode(), pe.getMessage());
        } catch (Exception e) {
            return ResultVO.createError(e.getMessage());
        }
    }

    /**
     * 提现至平台佣金接口
     */
    @PostMapping("/accountTransfer")
    public ResultVO<?> transferToPlatformCommissionAccount(@RequestBody UserAccountWithdrawalDTO withdrawalDTO) {
        try {
            paymentLoanService.transferToPlatformCommissionAccount(withdrawalDTO);
            return ResultVO.createSuccess();
        } catch (PaymentException pe) {
            log.error("transferToPlatformCommissionAccount error, {}", JSON.toJSONString(withdrawalDTO));
            return ResultVO.createError(pe.getErrCode(), pe.getMessage());
        } catch (Exception e) {
            log.error("transferToPlatformCommissionAccount error, {}", JSON.toJSONString(withdrawalDTO));
            return ResultVO.createError(e.getMessage());
        }
    }

    /**
     * 安贷还款计划金额对账，验证平安贷还款计划是否与业务数据金额一致
     */
    @PostMapping(value = "/check_loan_amount")
    public ResultVO loanDetail() {
        paymentLoanService.checkLoanAmount(true);
        return ResultVO.createSuccess();
    }

    /**
     * 平安 还款计划回盘文件 查询
     */
    @RequestMapping(value = "/repaymentPlan/query", method = RequestMethod.POST)
    public String queryRepaymentPlan(@RequestBody PinganRepaymentPlanParamVO param) {
        log.info("queryRepaymentPlan:{}",JSONObject.toJSONString(param));
        if (param.getPage() == null) {
            param.setPage(1);
        }
        if (param.getPage() > 20) {
            param.setPage(20);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(20);
        }
        ResultPageVo<List<PayFinanceRefundPlanVo>> result = paymentLoanService.queryByPage(param);
        return JSONObject.toJSONString(result);
    }

    /**
     * 平安 还款计划回盘文件 导出
     */
    @RequestMapping(value = "/repaymentPlan/export", method = RequestMethod.POST)
    public void exportRepaymentPlan(@RequestBody PinganRepaymentPlanParamVO param, HttpServletRequest request, HttpServletResponse response) {
        log.info("exportRepaymentPlan:{}",param);
        final List<PayFinanceRefundPlan> list = paymentLoanService.export(param);
        String excelFileName = "平安还款计划.xlsx";
        String sheetName = "还款计划";
        String headers[] = Constants.PINGAN_REPAMENT_PALN;
        String fieldNames[] = Constants.PINGAN_REPAMENT_PALN_FIELD;
        try {
            ExportExcelUtil.createExcelDateFormat2(response, request, excelFileName, sheetName, headers, fieldNames, list, true, null);
            log.info("exportRepaymentPlan end ");
        } catch (IOException e) {
            log.error("exportRepaymentPlan excel导出错误{}", JSON.toJSONString(param), e);
        }
    }

}
